package com.android.lovely.ui.viewmodel

import androidx.lifecycle.viewModelScope
import com.android.lovely.api.service.botService
import com.android.lovely.const.ChatChange
import com.android.lovely.data.HomeTabData
import com.android.lovely.framework.BaseViewModel
import com.android.lovely.framework.doContinuousOperation
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.user.UserManager
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.post
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow

/**
 *
 * @author why
 * @date 2025/3/10 15:09
 */
class HomeViewModel: BaseViewModel() {
    private val _homeTabList = MutableSharedFlow<List<HomeTabData>>(0, 1, BufferOverflow.DROP_OLDEST)
    val homeTabList: SharedFlow<List<HomeTabData>> get() = _homeTabList

    private val _homeTabList2 = MutableSharedFlow<List<HomeTabData>>(0, 1, BufferOverflow.DROP_OLDEST)
    val homeTabList2: SharedFlow<List<HomeTabData>> get() = _homeTabList2

    private val _nsfwSwitchFlow = MutableSharedFlow<Int>(0, 1, BufferOverflow.DROP_OLDEST)
    val nsfwSwitchFlow: SharedFlow<Int> get() = _nsfwSwitchFlow
    fun getTabs() {
        viewModelScope.launchSafety {
            doContinuousOperation {
                _homeTabList.emit(botService.getHomeTabs())
            }
        }
    }

    fun refreshGetTabs() {
        viewModelScope.launchSafety {
            doContinuousOperation {
                _homeTabList2.emit(botService.getHomeTabs())
            }
        }
    }

    fun changeNsfw(i: Int) {
        UserManager.userInfo = UserManager.userInfo?.copy(nsfwStatus = i)
        viewModelScope.launchWithLoading {
            UserManager.updateAuth {
                this.nsfw = i
            }
            doContinuousOperation {
                refreshGetTabs()
                FlowBus.post(ChatChange())
                _nsfwSwitchFlow.emit(i)
            }
        }
    }
}